using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using XmlObjects.XmlWriter;

namespace XmlObjects
{
	public class Dehydrator<T> : XmlWriterBase where T : class
	{
		private Type typeToDehydrate;
		private Dictionary<PropertyInfo, IXmlWriter> xmlWriterMap = new Dictionary<PropertyInfo, IXmlWriter>();

		public Dehydrator(ElementToPropertyMap elementToPropertyMap) : base(elementToPropertyMap)
		{
			typeToDehydrate = typeof (T);
//			foreach (PropertyInfo propertyInfo in typeToDehydrate.GetProperties())
//			{
//				if (Attribute.IsDefined(propertyInfo, typeof (PropertyAttribute)))
//				{
//					IXmlWriter writer = XmlWriterFactory.GetWriter(propertyInfo);
//					xmlWriterMap.Add(propertyInfo, writer);
//				}
//			}
		}

		public override void Append(object obj, XmlNode node)
		{
			if (obj == null)
				return;
			XmlNode newNode = elementToPropertyMap.AppendNodeTo(node, obj.GetType());
			WriteLocal(obj, newNode);
		}

		public override void WriteLocal(object obj, XmlNode node)
		{
			if (obj == null)
				return;

			foreach (PropertyInfo propertyInfo in typeToDehydrate.GetProperties())
			{
				if (Attribute.IsDefined(propertyInfo, typeof (PropertyAttribute)))
				{
					object value = propertyInfo.GetValue(obj, null);
					if (value != null)
					{
						IXmlWriter writer = XmlWriterFactory.GetWriter(propertyInfo);
						writer.Append(value, node);
					}
				}
			}
		}
	}
}